package com.juyu.reader.pc.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.juyu.reader.pc.common.Constants;
import com.juyu.reader.pc.common.PageDirective;
import com.juyu.reader.pc.model.Book;
import com.juyu.reader.pc.model.BookChapter;
import com.juyu.reader.pc.model.Page;
import com.juyu.reader.pc.service.BookChapterService;
import com.juyu.reader.pc.service.BookService;

@Controller
@RequestMapping("/rank")
public class RankingController extends BaseController {

	@Autowired
	private BookService bookService;
	@Autowired
	private BookChapterService bookChapterService;

	/**
	 * 排行
	 * @param request
	 * @param searchBook
	 * @param page
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView bookRanking(HttpServletRequest request, Book searchBook, Page page) {
		this.setNavIndex(request, 3);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		page.setLimit(30);
		searchBook.setOffset(page.getOffset());
		searchBook.setLimit(page.getLimit());
		List<Book> bookList = bookService.findBookByRank(searchBook);
		for (Book b : bookList) {
			List<BookChapter> latestChapters = bookChapterService.findBookChapterLatest(b.getBookId());
			if (latestChapters.size() >= 1) {
				b.setBookLatestChapterId(latestChapters.get(0).getChapterId());
				b.setBookLatestChapter(latestChapters.get(0).getChapterName());
			}
		}
		int count = bookService.countBookByRank(searchBook);
		attrMap.put("sourceUrl", Constants.SOURCE_URL);
		attrMap.put("bookList", bookList);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request, page.getLimit()));

		return this.packModeAndView(request, "/book/rankList", null, attrMap);
	}
}
